//
//  HWGameLiveController.swift
//  HWanGame
//
//  Created by 王昌健 on 2022/1/5.
//

import UIKit
import JXSegmentedView

class HWGameLiveController: HWBaseViewController {
    var collectionView:UICollectionView!
    let collectionProtocol = HWGameLiveProtocol()
    var httpManager = HWGameLiveHttpManager()
    let mutDataArr = NSMutableArray()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        initFrame()
        
        addRefresh()
        
        addAction()
        
        loadData()
        
    }
    
}

extension HWGameLiveController {
    private func initUI() -> Void {
        navigationView.isHidden = true
        
        view.backgroundColor = .colorWithHexString(hexString: "#F7F7F7")
        
        let flowL = UICollectionViewFlowLayout.init()
        flowL.minimumLineSpacing = 7*widthScale
        flowL.minimumInteritemSpacing = 7*widthScale
        flowL.scrollDirection = .vertical
        collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: flowL)
        collectionView.delegate = collectionProtocol
        collectionView.dataSource = collectionProtocol
        collectionView.backgroundColor = .white
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(HWGameLiveCell.self, forCellWithReuseIdentifier: "HWGameLiveCell")
        view.addSubview(collectionView)
        collectionView.ly_emptyView = LYEmptyView.empty(withImageStr: "", titleStr: "", detailStr: "暂无数据")
        collectionView.ly_emptyView.contentViewOffset = -40
    }
    
    private func initFrame() -> Void {
        collectionView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(2*widthScale)
        }
    }
}

extension HWGameLiveController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

extension HWGameLiveController {
    func addRefresh() -> () {
        
        collectionView.mj_header = MJRefreshNormalHeader()
        collectionView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        collectionView.mj_footer = MJRefreshBackNormalFooter()
        collectionView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
    }
    
    
    @objc func loadNewData() -> () {
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        
        self.httpManager.getGameLiveRoomsFooter(para: ["type":"tagId"]) { modelArr in
            self.collectionView.mj_footer?.endRefreshing()
            if modelArr.count > 0 {
                self.mutDataArr.addObjects(from: modelArr)
                
            }
            self.collectionProtocol.models = self.mutDataArr as? [HWGameLiveListModel]
            self.collectionView.reloadData()
        } failure: { error in
            if error == "暂无房间"{
                self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            }else{
                self.collectionView.mj_footer?.endRefreshing()
            }
        }
        
    }
    
    func loadData() -> Void {
        httpManager.getGameLiveRooms(para: ["type":"tagId"]) { models in
            
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            if models.count > 0 {
                self.mutDataArr.removeAllObjects()
                self.mutDataArr.addObjects(from: models)
            }
            self.collectionProtocol.models = self.mutDataArr as? [HWGameLiveListModel]
            self.collectionView.reloadData()
        } failure: { error in
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
        
    }
}
//HWGameLiveHttpManager *httpManager = [[HWGameLiveHttpManager alloc] init];
//
//[httpManager getGameLiveImInfoWithSuccess:^(NSDictionary * dic) {
//    NSLog(@"%@",dic);
////            HWUniversal.jsonstring
//
//    [httpManager getGameLiveConfigWithSuccess:^(NSString * appId) {
//        [[V2TIMManager sharedInstance] initSDK:[appId intValue] config:[[V2TIMSDKConfig alloc] init] listener:self];
//        [[V2TIMManager sharedInstance] login:dic[@"live_uid"] userSig:dic[@"live_sign"] succ:^{
//
//            V2TIMUserFullInfo *info = [[V2TIMUserFullInfo alloc] init];
//            info.nickName = [HWLocallyStoredData getUserName];
//            info.faceURL = [HWLocallyStoredData getUserFace];
//
////                    info.customInfo = @{@"color":[HWUniversal JSONStringToDataWithJson:@"adsfaf"]};
//            [[V2TIMManager sharedInstance] setSelfInfo:info succ:^{
//
//            } fail:^(int code, NSString *desc) {
//
//            }];
//
//        } fail:^(int code, NSString *desc) {
//            NSLog(@"%@,code=%d",desc,code);
//        }];
//    } failure:^(NSString * error) {
//
//    }];
//
//} failure:^(NSString * error) {
//
//}];
extension HWGameLiveController {
    func addAction() -> Void {
        collectionProtocol.jumpToLiveRoom = {
            model in
            if model.status == "0" {
                self.view.showHUD(title: "该房间暂未开播")
                return
            }
            if HWLocallyStoredData.getLoginUserID().count>0{
                self.view.showWaitHUD()
                let loginStatus = V2TIMManager.sharedInstance().getLoginStatus()
                if loginStatus == .STATUS_LOGINED {
                    self.httpManager.getGameLiveRoomInfo(roomId: model.room_id) { roomInfo in
                        
                        V2TIMManager.sharedInstance().getGroupsInfo([model.room_id]) { [weak self] groupInfos in
                            guard self != nil else { return }
                            guard let groupInfo = groupInfos?.first else { return }
                            if groupInfo.resultCode == 0 {
                                HWGameLiveImManager.shared.enterRoom(roomId: model.room_id) { code, message in
                                    print(message)
                                }
                                let gameLiveRoomController = HWGameLiveRoomController()
                                roomInfo.ownerId = groupInfo.info.owner
                                gameLiveRoomController.liveModel = roomInfo
                                gameLiveRoomController.closeCallBack = {
                                    self?.loadData()
                                }
                                self?.view.hideHUD()
                                self?.navigationController?.pushViewController(gameLiveRoomController, animated: true)
                                
                            }else{
                                self?.view.hideHUD()
                                self?.view.showHUD(title: groupInfo.resultMsg)
                            }
                            
                        } fail: { code, message in
                            print(message ?? "")
                            self.view.showHUD(title: message)
                        }
                        
                    } failure: { error in
                        print(error)
                        self.view.showHUD(title: error)
                    }
                }else {
                    self.view.showWaitHUD()
                    self.httpManager.getGameLiveImInfo { dic in
                        self.httpManager.getGameLiveConfig { appId in
                            V2TIMManager.sharedInstance().initSDK(Int32(appId) ?? 0, config: V2TIMSDKConfig(), listener: self)
                            V2TIMManager.sharedInstance().login(dic["live_uid"] as? String, userSig: dic["live_sign"] as? String) {
                                HWMineHttpManager().getMineHomeInfo { mod in
                                    UserDefaults.standard.set(mod.user.face, forKey: "userHeadImage")
                                    HWLocallyStoredData.setUserName(mod.user.user_name)
                                    HWLocallyStoredData.setUserFace(mod.user.face)
                                    let info = V2TIMUserFullInfo()
                                    info.nickName = HWLocallyStoredData.getUserName()
                                    info.faceURL = HWLocallyStoredData.getUserFace()
                                    V2TIMManager.sharedInstance().setSelfInfo(info) {
                                        self.httpManager.getGameLiveRoomInfo(roomId: model.room_id) { roomInfo in
                                            
                                            V2TIMManager.sharedInstance().getGroupsInfo([model.room_id]) { [weak self] groupInfos in
                                                guard self != nil else { return }
                                                guard let groupInfo = groupInfos?.first else { return }
                                                if groupInfo.resultCode == 0 {
                                                    HWGameLiveImManager.shared.enterRoom(roomId: model.room_id) { code, message in
                                                        print(message)
                                                    }
                                                    let gameLiveRoomController = HWGameLiveRoomController()
                                                    roomInfo.ownerId = groupInfo.info.owner
                                                    gameLiveRoomController.liveModel = roomInfo
                                                    gameLiveRoomController.closeCallBack = {
                                                        self?.loadData()
                                                    }
                                                    self?.view.hideHUD()
                                                    self?.navigationController?.pushViewController(gameLiveRoomController, animated: true) 
                                                }else{
                                                    self?.view.showHUD(title: groupInfo.resultMsg)
                                                }
                                                
                                            } fail: { code, message in
                                                print(message ?? "")
                                                self.view.showHUD(title: message)
                                            }
                                            
                                        } failure: { error in
                                            print(error)
                                            self.view.showHUD(title: error)
                                        }
                                    } fail: { code, desc in
                                        self.view.showHUD(title: desc)
                                    }
                                } failure: { error in
                                    self.view.showHUD(title: error)
                                }
                                
                            } fail: { code, desc in
                                self.view.showHUD(title: desc)
                            }
                            
                        } failure: { error in
                            self.view.showHUD(title: error)
                        }
                    } failure: { error in
                        self.view.showHUD(title: error)
                    }
                    
                }
                
                
                
            }else{
                let loginController = HWLoginController()
                self.navigationController?.pushViewController(loginController, animated: true)
            }
        }
    }
    
}
extension HWGameLiveController:V2TIMSDKListener {
    
}
//class JWellUserModel: NSObject,NSCoding {
//   let filePath = NSHomeDirectory() + "/Documents/contacts.data"
//    var mainUserId: Int?
//    var id: Int?
//    var key: String?
//    var name: String?
//    // 解档
//    required init?(coder aDecoder: NSCoder) {
//        super.init()
//        self.mainUserId   = aDecoder.decodeObject(forKey: "mainUserId") as? Int
//        self.id           = aDecoder.decodeObject(forKey: "id") as? Int
//        self.key          = aDecoder.decodeObject(forKey: "key") as? String
//        self.name         = aDecoder.decodeObject(forKey: "name") as? String
//    }
//
//    // 归档
//    func encode(with aCoder: NSCoder) {
//        aCoder.encode(self.mainUserId,forKey: "mainUserId")
//        aCoder.encode(self.id,forKey: "id")
//        aCoder.encode(self.key,forKey: "key")
//        aCoder.encode(self.name,forKey: "name")
//    }
//
//    override init() {
//
//    }
//
//}
//
////这里我用的HandyJson，出来的时候是一个```json```字符串我转了一下
//class JWellLoginNetWorking: NSObject {
//    var result = NSDictionary()
//
//    lazy var model: (JWellUserModel) = {
//        let model = JWellUserModel()
//        return model
//    }()
//
//}
//          extension JWellLoginNetWorking{
//    func loginNetWorking(userName: String, passWord: String) -> (){
//        var parmas: [String: Any] = Dictionary()
//        parmas["username"] = userName
//        parmas["password"] = passWord
//        NetWorkRequest(.login(params: parmas), completion: { (response) -> (Void) in
//            let dicData = getDictionaryFromJSONString(jsonString: response)
//            self.result = dicData["result"] as! NSDictionary
//            self.model.key = (self.result["key"] as! String)
//            self.model.name = (self.result["name"] as! String)
//            self.model.id = (self.result["id"] as! Int)
//            self.model.mainUserId = (self.result["mainUserId"] as! Int)
//
//            let data = NSMutableData()
//            let archive = NSKeyedArchiver(forWritingWith: data)
//            archive.encode(self.model, forKey: "userKey")
//            archive.finishEncoding()
//            data.write(toFile: self.model.filePath, atomically: true)
//
//            let tab = JWellCTabBarController()
//            kAppWindow??.rootViewController = tab
//            kAppWindow??.makeKeyAndVisible()
//
//        }, failed: { (str) -> (Void) in
//
//        }) { () -> (Void) in
//
//        }
//    }
//
//
//}
//
//var headers: [String : String]? {
//    let model = JWellUserModel()
//    var key = ""
//    let fileData = NSMutableData(contentsOfFile: model.filePath)
//    if fileData != nil {
//        let unarchiver = NSKeyedUnarchiver(forReadingWith: fileData! as Data)
//        let saveUser = unarchiver.decodeObject(forKey: "userKey") as! JWellUserModel
//        unarchiver.finishDecoding()
//        if saveUser.key != nil {
//            key = saveUser.key!
//        }
//    }
//    return ["Content-Type":"application/json","Authorization":"Bearer " + key]
//}
